<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>监控详情页 - n8n工作流监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', '微软雅黑', 'PingFang SC', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Source Han Sans CN', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .back-btn {
            background: white;
            color: #667eea;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            text-decoration: none;
            display: inline-block;
        }
        
        .back-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .detail-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .detail-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        
        .stat-card .label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 10px;
        }
        
        .stat-card .value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .user-list {
            max-height: 600px;
            overflow-y: auto;
        }
        
        .user-item {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .user-item.clickable {
            position: relative;
        }
        
        .user-item.clickable::after {
            content: '💬';
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 1.2em;
            opacity: 0.6;
            transition: opacity 0.3s;
        }
        
        .user-item.clickable:hover::after {
            opacity: 1;
        }
        
        .user-item:hover {
            background: #f8f9fa;
            border-color: #667eea;
        }
        
        .user-item.active {
            background: #e3f2fd;
            border-color: #667eea;
        }
        
        .user-name {
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }
        
        .user-meta {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 10px;
        }
        
        .user-content {
            color: #555;
            line-height: 1.6;
        }
        
        .user-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .user-actions {
            display: flex;
            gap: 10px;
        }
        
        .chat-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.85em;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .chat-btn:hover {
            background: #5a6fd8;
            transform: translateY(-1px);
        }
        
        .message-detail {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .message-detail h3 {
            color: #333;
            margin-bottom: 15px;
        }
        
        .message-content {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
        }
        
        .message-meta {
            font-size: 0.85em;
            color: #999;
            margin-bottom: 10px;
        }
        
        .loading {
            text-align: center;
            color: white;
            font-size: 1.5em;
            padding: 50px;
        }
        
        .error-message {
            background: #fee2e2;
            color: #991b1b;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin: 20px 0;
        }
        
        .no-data {
            text-align: center;
            color: #666;
            padding: 40px;
            font-size: 1.1em;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 id="pageTitle">监控详情页</h1>
            <p id="pageSubtitle">加载中...</p>
            <a href="index.html" class="back-btn">← 返回主页</a>
        </div>
        
        <div id="loadingMessage" class="loading">
            正在加载数据...
        </div>
        
        <div id="errorMessage" class="error-message" style="display: none;">
            ❌ 无法加载数据。请确保已运行 monitor.py 生成报告文件。
        </div>
        
        <div id="content" style="display: none;">
            <!-- 统计概览 -->
            <div class="detail-section">
                <h2>统计概览</h2>
                <div class="stats-grid" id="statsGrid">
                    <!-- 动态填充 -->
                </div>
            </div>
            
            <!-- 用户列表 -->
            <div class="detail-section">
                <h2>涉及用户列表</h2>
                <div class="user-list" id="userList">
                    <!-- 动态填充 -->
                </div>
            </div>
            
            <!-- 消息详情 -->
            <div class="detail-section" id="messageDetailSection" style="display: none;">
                <h2>消息详情</h2>
                <div id="messageDetail">
                    <!-- 动态填充 -->
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 获取URL参数
        function getUrlParameter(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        // 加载监控数据
        async function loadMonitorData() {
            try {
                const response = await fetch('static/monitor_report.json');
                if (!response.ok) throw new Error('无法加载报告文件');
                
                const data = await response.json();
                const detailType = getUrlParameter('type');
                
                displayDetailData(data, detailType);
                
                document.getElementById('loadingMessage').style.display = 'none';
                document.getElementById('content').style.display = 'block';
                
            } catch (error) {
                console.error('加载数据失败:', error);
                document.getElementById('loadingMessage').style.display = 'none';
                document.getElementById('errorMessage').style.display = 'block';
            }
        }
        
        // 显示详情数据
        function displayDetailData(data, detailType) {
            let title, subtitle, stats, users, issues;
            
            switch (detailType) {
                case 'sensitive':
                    title = '敏感信息详情';
                    subtitle = '包含敏感词的消息详情';
                    stats = {
                        '总AI消息数': data.content_analysis.total_ai_messages,
                        '敏感词检测': data.content_analysis.sensitive_word_count,
                        '检测率': data.content_analysis.sensitive_word_count / data.content_analysis.total_ai_messages * 100
                    };
                    users = data.content_analysis.issues || [];
                    break;
                    
                case 'salary':
                    title = '薪资信息详情';
                    subtitle = '包含薪资信息的消息详情';
                    
                    // 从真实聊天数据中统计薪资信息
                    const salaryStats = analyzeSalaryInfo(data.reply_rate_details.details);
                    
                    stats = {
                        '总AI消息数': salaryStats.total_ai_messages,
                        '薪资信息提及': salaryStats.salary_mentions,
                        '提及率': salaryStats.salary_rate + '%'
                    };
                    users = salaryStats.issues || [];
                    break;
                    
                case 'photo_request':
                    title = '索要照片信息详情';
                    subtitle = '包含索要照片信息的消息详情';
                    
                    // 从真实聊天数据中统计索要照片信息
                    const photoStats = analyzePhotoRequestInfo(data.reply_rate_details.details);
                    
                    stats = {
                        '总AI消息数': photoStats.total_ai_messages,
                        '索要照片信息': photoStats.photo_requests,
                        '索要率': photoStats.photo_request_rate + '%'
                    };
                    users = photoStats.issues || [];
                    break;
                    
                case 'greeting':
                    title = '打招呼信息详情';
                    subtitle = '主动打招呼的消息详情';
                    
                    // 从报告数据中获取打招呼信息
                    const greetingStats = data.greeting_analysis || {};
                    
                    stats = {
                        '总AI消息数': greetingStats.total_ai_messages || 0,
                        '打招呼消息数': greetingStats.greeting_count || 0,
                        '打招呼率': greetingStats.greeting_rate ? greetingStats.greeting_rate + '%' : '0%'
                    };
                    users = greetingStats.issues || [];
                    break;
                    
                default:
                    title = '未知类型详情';
                    subtitle = '请指定正确的详情类型';
                    stats = {};
                    users = [];
            }
            
            // 更新页面标题
            document.getElementById('pageTitle').textContent = title;
            document.getElementById('pageSubtitle').textContent = subtitle;
            
            // 显示统计信息
            displayStats(stats);
            
            // 显示用户列表
            displayUsers(users);
        }
        
        // 显示统计信息
        function displayStats(stats) {
            const container = document.getElementById('statsGrid');
            
            if (Object.keys(stats).length === 0) {
                container.innerHTML = '<div class="no-data">暂无统计数据</div>';
                return;
            }
            
            container.innerHTML = Object.entries(stats).map(([label, value]) => `
                <div class="stat-card">
                    <div class="label">${label}</div>
                    <div class="value">${typeof value === 'number' ? value.toFixed(2) : value}</div>
                </div>
            `).join('');
        }
        
        // 显示用户列表
        function displayUsers(users) {
            const container = document.getElementById('userList');
            
            if (users.length === 0) {
                container.innerHTML = '<div class="no-data">暂无相关用户数据</div>';
                return;
            }
            
            container.innerHTML = users.map((user, index) => `
                <div class="user-item clickable" onclick="navigateToUserChat(${user.candidate_id || index})">
                    <div class="user-info">
                        <div class="user-name">${user.candidate_name}</div>
                        <div class="user-actions">
                            <button class="chat-btn" onclick="event.stopPropagation(); navigateToUserChat(${user.candidate_id || index})">
                                查看聊天记录
                            </button>
                        </div>
                    </div>
                    <div class="user-meta">时间: ${user.created_at}</div>
                    <div class="user-content">${user.content}</div>
                </div>
            `).join('');
        }
        
        // 显示消息详情
        function showMessageDetail(index) {
            const users = getCurrentUsers();
            if (!users || !users[index]) return;
            
            const user = users[index];
            const detailSection = document.getElementById('messageDetailSection');
            const detailContainer = document.getElementById('messageDetail');
            
            // 移除其他活跃状态
            document.querySelectorAll('.user-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 设置当前项为活跃状态
            event.currentTarget.classList.add('active');
            
            // 显示消息详情
            detailContainer.innerHTML = `
                <div class="message-content">
                    <div class="message-meta">用户: ${user.candidate_name} | 时间: ${user.created_at}</div>
                    <div>${user.content}</div>
                </div>
            `;
            
            detailSection.style.display = 'block';
        }
        
        // 获取当前用户列表
        function getCurrentUsers() {
            const detailType = getUrlParameter('type');
            // 这里需要根据类型返回对应的用户数据
            // 由于数据结构的限制，这里简化处理
            return [];
        }
        
        // 跳转到用户聊天记录页面
        function navigateToUserChat(candidateId) {
            try {
                if (!candidateId) {
                    console.error('缺少候选人ID');
                    return;
                }
                
                const chatUrl = getUserChatUrl(candidateId);
                window.location.href = chatUrl;
                
            } catch (error) {
                console.error('跳转到聊天记录失败:', error);
                alert('跳转失败，请稍后重试');
            }
        }
        
        // 生成用户聊天记录URL
        function getUserChatUrl(candidateId) {
            return `user_chat.html?candidate_id=${candidateId}`;
        }
        
        // 分析薪资信息
        function analyzeSalaryInfo(candidates) {
            let totalAiMessages = 0;
            let salaryMentions = 0;
            const issues = [];
            
            // 薪资相关关键词
            const salaryKeywords = ['工资', '薪资', '薪水', '待遇', '收入', '报酬', '元', '钱', '日结', '月结', '保底', '提成'];
            
            candidates.forEach(candidate => {
                if (candidate.chat_history) {
                    candidate.chat_history.forEach(msg => {
                        if (msg.sender === '我') {
                            totalAiMessages++;
                            
                            // 检查是否包含薪资信息
                            const hasSalaryInfo = salaryKeywords.some(keyword => 
                                msg.content.includes(keyword)
                            );
                            
                            if (hasSalaryInfo) {
                                salaryMentions++;
                                issues.push({
                                    candidate_id: candidate.id,
                                    candidate_name: candidate.name,
                                    content: msg.content,
                                    created_at: msg.time,
                                    type: 'salary_mention'
                                });
                            }
                        }
                    });
                }
            });
            
            const salaryRate = totalAiMessages > 0 ? (salaryMentions / totalAiMessages * 100).toFixed(2) : 0;
            
            return {
                total_ai_messages: totalAiMessages,
                salary_mentions: salaryMentions,
                salary_rate: salaryRate,
                issues: issues
            };
        }

        // 分析索要照片信息
        function analyzePhotoRequestInfo(candidates) {
            let totalAiMessages = 0;
            let photoRequests = 0;
            const issues = [];
            
            // 索要照片相关关键词
            const photoKeywords = ['照片', '生活照', '看看', '评估', '上镜', '整体感觉', '发几张', '发张'];
            
            candidates.forEach(candidate => {
                if (candidate.chat_history) {
                    candidate.chat_history.forEach(msg => {
                        if (msg.sender === '我') {
                            totalAiMessages++;
                            
                            // 检查是否包含索要照片信息
                            const hasPhotoRequest = photoKeywords.some(keyword => 
                                msg.content.includes(keyword)
                            );
                            
                            if (hasPhotoRequest) {
                                photoRequests++;
                                issues.push({
                                    candidate_id: candidate.id,
                                    candidate_name: candidate.name,
                                    content: msg.content,
                                    created_at: msg.time,
                                    type: 'photo_request'
                                });
                            }
                        }
                    });
                }
            });
            
            const photoRequestRate = totalAiMessages > 0 ? (photoRequests / totalAiMessages * 100).toFixed(2) : 0;
            
            return {
                total_ai_messages: totalAiMessages,
                photo_requests: photoRequests,
                photo_request_rate: photoRequestRate,
                issues: issues
            };
        }

        // 页面加载时执行
        window.addEventListener('DOMContentLoaded', loadMonitorData);
    </script>
</body>
</html>
